/*
	i8254.c
	
	8254 programmable timer control code
	
	Meng Sun(c) leon.meng.sun@gmail.com
	Source code released under LGPLv3
	https://www.gnu.org/licenses/lgpl-3.0.txt
*/

#include "i8254.h"
#include "i8259a.h"

static uint32 epocCounterHi = 0x00000000;

static uint32 epocCounterLo = 0x00000000;

static uint32 waitCounter = 0x00000000;

void waitTillMillisecond(uint8 t){

	waitCounter = getEpocCounterLo();
	while (getEpocCounterLo() != waitCounter + t) {}
	return;
}

static void callback i8254InterruptService(void){
	
	if (epocCounterLo != 0xffffffff){
		++epocCounterLo;
	} else if (epocCounterHi != 0xffffffff){
		epocCounterLo = 0x00000000;
		++epocCounterHi;
	} else {
		epocCounterHi = 0x00000000;
		epocCounterLo = 0x00000000;
	}
	return;
}

uint32 getEpocCounterHi(void){

	return epocCounterHi;
}

uint32 getEpocCounterLo(void){

	return epocCounterLo;
}

void i8254Init(void){

	CONTROL = 0x34;
	CTR0 = 0x33;
	CTR1 = 0x07;
	
	seti8254ISRCallback(&i8254InterruptService);

	return;
}

